package com.skyline.wo.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.skyline.base.dao.impl.BaseDaoImpl;
import com.skyline.base.exception.NoResourceException;
import com.skyline.common.bean.Page;
import com.skyline.common.cache.annotation.Cache;
import com.skyline.common.cache.annotation.CacheCategoryType;
import com.skyline.common.cache.annotation.CacheDelete;
import com.skyline.common.cache.annotation.Fk;
import com.skyline.common.cache.annotation.Param;
import com.skyline.wo.dao.VideoDao;
import com.skyline.wo.mapper.VideoMapper;
import com.skyline.wo.model.Video;

@Repository("videoDao")
public class VideoDaoImpl extends BaseDaoImpl implements VideoDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/*
	 * insert into video (ownerId ,ownerPortrait
	 * ,ownerNickname,createTime,updateTime,activity ,title,thumbnail
	 * ,summary,time,source ,pageUrl,flashUrl,htmlCode)values(? ,?
	 * ,?,current_timestamp,current_timestamp,'NORMAL' ,?,? ,?,?,? ,?,?,?)
	 */
	@Value("${VideoDao.insertVideo}")
	private String insertVideoSql;

	@Value("${VideoDao.queryVideoById}")
	private String queryVideoByIdSql;

	@Value("${VideoDao.updateVideoVisitNum}")
	private String updateVideoVisitNumSql;
	
	@Value("${VideoDao.queryVideoByOwnerId}")
	private String queryVideoByOwnerIdSql;


//	@Value("${VideoDao.updateVideoDigest}")
//	private String updateVideoDigestSql;

	@Override
	@CacheDelete(type = CacheCategoryType.VIDEO)
	public long insertVideo(@Fk Long ownerId, String ownerPortrait, String ownerNickname, String title, String thumbnail, String summary,
			String time, String source, String pageUrl, String flashUrl, String htmlCode) {
		return insertWithIdReturn(insertVideoSql, ownerId, ownerPortrait, ownerNickname, title, thumbnail, summary, time, source, pageUrl,
				flashUrl, htmlCode);
	}

//	@Override
//	public void updateVideoDigest(Long id, String digest) {
//		jdbcTemplate.update(updateVideoDigestSql, id, digest);
//	}

	@Override
	@Cache(keyPattern = "video-:id", type = CacheCategoryType.VIDEO)
	public Video queryVideoById(@Param("id") Long id) throws NoResourceException {
		try {
			Video video = jdbcTemplate.queryForObject(queryVideoByIdSql, VideoMapper.getMapper(), id);
			return video;
		} catch (Exception e) {
			throw new NoResourceException("id为" + id + "的视频不存在");
		}
	}

	@Override
	public void updateVideoVisitNum(Long id) {
		jdbcTemplate.update(updateVideoVisitNumSql, id);
	}
	
	@Override
	@Cache(keyPattern = "video-l-:oid", type = CacheCategoryType.VIDEO,pagination=true)
	public  List<Video> queryVideoByOwnerId(@Param("oid") @Fk Long ownerId,Page page){
		
		return getPaginationResult(queryVideoByOwnerIdSql,page,VideoMapper.getMapper(),ownerId);
	}
}
